﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Collections.Generic;
using TMPro;
using UnityEngine.UI;


public class SongDataReader : MonoBehaviour
{

    public string songFolderPath = "Songs"; 
    public List<SongData> allSongData = new List<SongData>();
    public Transform songListContainer; 
    public GameObject songListItemPrefab; 

    public TextMeshProUGUI titleTextBig;
    public TextMeshProUGUI titleTextSmall;
    public TextMeshProUGUI artistText;
    public TextMeshProUGUI bpmText;
    public TextMeshProUGUI offsetText;
    public TextMeshProUGUI difficultyEasyText;
    public TextMeshProUGUI difficultyMediumText;
    public TextMeshProUGUI difficultyHardText;
    public TextMeshProUGUI designerText;



    void Start()
    {
        ReadAllSongFiles();
        UpdateSongListUI();
        string rootPath = Path.Combine(Application.streamingAssetsPath, songFolderPath);
        Debug.Log("当前歌曲根路径：" + rootPath);
    }

    public void ReadAllSongFiles()
    {
        string fullRootPath = Path.Combine(Application.streamingAssetsPath, "Songs");

        if (!Directory.Exists(fullRootPath))
        {
            Debug.LogError($"歌曲根文件夹不存在！路径：{fullRootPath}"); return;
        }

        string[] songSubFolders = Directory.GetDirectories(fullRootPath);
        foreach (string subFolder in songSubFolders)
        {
            string songTxtPath = Path.Combine(subFolder, "SongData.txt");
            if (File.Exists(songTxtPath))
            {
                SongData parsedSong = ParseSingleSongTxt(songTxtPath);
                if (parsedSong != null)
                {
                    allSongData.Add(parsedSong);
                    Debug.Log($"成功读取歌曲：{parsedSong.title}（艺术家：{parsedSong.artist}）");
                }
            }
            else
            {
                Debug.LogWarning($"子文件夹中未找到SongData.txt：{subFolder}");
            }
        }

        OnSongDataReadComplete();
    }

    private SongData ParseSingleSongTxt(string txtPath)
    {
        SongData song = new SongData();
        try
        {
            string[] allLines = File.ReadAllLines(txtPath, System.Text.Encoding.UTF8);

            Debug.Log($"开始解析文件：{txtPath}");
            Debug.Log($"文件内容行数：{allLines.Length}");
            foreach (string line in allLines)
            {
                string trimmedLine = line.Trim();
                if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("//"))
                    continue;

                ParseLineToSongData(trimmedLine, song);
            }

            if (string.IsNullOrEmpty(song.title))
            {
                Debug.LogError($"歌曲txt缺少title字段：{txtPath}"); return null;
            }
            if (string.IsNullOrEmpty(song.artist))
            {
                Debug.LogError($"歌曲{song.title}缺少artist字段：{txtPath}"); return null;
            }

            return song;
        }
        catch (Exception e)
        {
            Debug.LogError($"解析歌曲txt失败！路径：{txtPath}，错误：{e.Message}"); return null;
        }
    }

    // 按行解析内容，赋值到SongData对象
private void ParseLineToSongData(string line, SongData song)
{
    // 更灵活的正则表达式，支持多种分隔符（: 或 - 或无分隔符）
    
    // 1. 匹配标题：支持 title:<内容> 或 title-<内容>
    if (Regex.IsMatch(line, @"^title\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^title\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        song.title = match.Groups[1].Value.Trim();
        Debug.Log($"解析到标题：{song.title}");
    }
    // 2. 匹配艺术家：支持 artist<内容> 或 artist-<内容>
    else if (Regex.IsMatch(line, @"^artist\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^artist\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        song.artist = match.Groups[1].Value.Trim();
        Debug.Log($"解析到艺术家：{song.artist}");
    }
    // 3. 匹配 BPM：支持 bpm<内容> 或 bpm:<内容>
    else if (Regex.IsMatch(line, @"^bpm\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^bpm\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        if (float.TryParse(match.Groups[1].Value.Trim(), out float bpm))
        {
            song.bpm = bpm;
            Debug.Log($"解析到BPM：{bpm}");
        }
        else
            Debug.LogWarning($"歌曲{song.title}的BPM格式错误：{line}");
    }
    // 4. 匹配偏移量：支持 offset<内容> 或 offset:<内容>
    else if (Regex.IsMatch(line, @"^offset\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^offset\s*[:-]?\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        if (float.TryParse(match.Groups[1].Value.Trim(), out float offset))
        {
            song.offset = offset;
            Debug.Log($"解析到偏移量：{offset}");
        }
        else
            Debug.LogWarning($"歌曲{song.title}的offset格式错误：{line}");
    }
    // 5. 匹配难度
    else if (Regex.IsMatch(line, @"^level_\s*<([^>]*)>\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^level_\s*<([^>]*)>\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        string levelName = match.Groups[1].Value.Trim();
        if (float.TryParse(match.Groups[2].Value.Trim(), out float levelValue))
        {
            song.levels.Add(new SongLevel
            {
                levelName = levelName,
                levelValue = levelValue
            });
            Debug.Log($"解析到难度：{levelName} - {levelValue}");
        }
        else
            Debug.LogWarning($"歌曲{song.title}的难度值格式错误：{line}");
    }
    // 6. 匹配设计师
    else if (Regex.IsMatch(line, @"^desinger\s*<([^>]*)>\s*<([^>]*)>$", RegexOptions.IgnoreCase))
    {
        Match match = Regex.Match(line, @"^desinger\s*<([^>]*)>\s*<([^>]*)>$", RegexOptions.IgnoreCase);
        string designerName = match.Groups[1].Value.Trim();
        string remark = match.Groups[2].Value.Trim();
        
        if (!string.IsNullOrEmpty(remark))
            designerName += $"（{remark}）";
        
        song.designers.Add(designerName);
        Debug.Log($"解析到设计师：{designerName}");
    }
    else
    {
        Debug.LogWarning($"未识别的歌曲字段格式：{line}");
    }
}
    private void OnSongDataReadComplete()
    {
        Debug.Log($"所有歌曲读取完成！共{allSongData.Count}首歌曲"); UpdateSongListUI();
        if (allSongData.Count > 0)
        {
            SongData firstSong = allSongData[0];  // 先定义变量
            ShowSongDetails(firstSong);
            Debug.Log($"第一首歌曲《{firstSong.title}》的难度：");
            foreach (var level in firstSong.levels)
            {
                Debug.Log($"- {level.levelName}：{level.levelValue}");
            }
        }
    }

    private void UpdateSongListUI()
    {
        // 添加空检查，避免错误
        if (songListContainer == null || songListItemPrefab == null)
        {
            Debug.LogWarning("UI引用未设置，跳过界面更新");
            return;
        }

        // 清空容器
        foreach (Transform child in songListContainer)
        {
            Destroy(child.gameObject);
        }

        // 为每首歌创建列表项
        foreach (var song in allSongData)
        {
            GameObject listItem = Instantiate(songListItemPrefab, songListContainer);

            // 使用 SongEntryUI 而不是 SongListItem
            SongEntryUI itemComponent = listItem.GetComponent<SongEntryUI>();
            if (itemComponent != null)
            {
                itemComponent.PopulateSongInfo(song);
            }

            // 添加点击事件
            Button button = listItem.GetComponent<Button>();
            if (button != null)
            {
                button.onClick.AddListener(() => ShowSongDetails(song));
            }
        }
    }

    public void ShowSongDetails(SongData song)
    {
        if (titleTextBig != null) titleTextBig.text = $"{song.title}";
        if (titleTextSmall != null) titleTextSmall.text = $"{song.title}";
        if (artistText != null) artistText.text = $"{song.artist}";
        if (bpmText != null) bpmText.text = $"{song.bpm}";
        if (offsetText != null) offsetText.text = $"{song.offset}";


        if (difficultyEasyText != null)
        {
            SongLevel easyLevel = song.levels.Find(level => level.levelName.Equals("Easy", StringComparison.OrdinalIgnoreCase));
            difficultyEasyText.text = easyLevel != null ? $"{easyLevel.levelValue}" : "Easy: -";
        }

        if (difficultyMediumText != null)
        {
            SongLevel mediumLevel = song.levels.Find(level => level.levelName.Equals("Medium", StringComparison.OrdinalIgnoreCase) ||
                                                             level.levelName.Equals("Normal", StringComparison.OrdinalIgnoreCase));
            difficultyMediumText.text = mediumLevel != null ? $"{mediumLevel.levelValue}" : "Medium: -";
        }

        if (difficultyHardText != null)
        {
            SongLevel hardLevel = song.levels.Find(level => level.levelName.Equals("Hard", StringComparison.OrdinalIgnoreCase));
            difficultyHardText.text = hardLevel != null ? $"{hardLevel.levelValue}" : "Hard: -";
        }

        if (designerText != null)
        {
            string designerInfo = "谱面作者:\n";
            foreach (var designer in song.designers)
            {
                designerInfo += $"{designer}\n";
            }
            designerText.text = designerInfo;
        }
    }

    public SongData GetSongDataByTitle(string songTitle)
    {
        return allSongData.Find(song => song.title.Equals(songTitle, StringComparison.OrdinalIgnoreCase));
    }
}